//constant for split keyvalue pairs
var pairro_spliter = '_@!@_';
var bilingualro_spliter = '@';
var splitlangro_spliter = '_@!@_';

//update dhx grid data
function grid_updateRowData(data, rId, rowdata) {
	if (data && data.rows && rId && rowdata) {
		for (var i in data.rows) {
			if (data.rows[i].id.toString()==rId) {
				data.rows[i].data = rowdata;
			}
		}
	}
	return data;
}

//filter dhx data by ids
function grid_filterDhxDataById(data, ids, noInd) {
	if (data && data.rows && ids && ids.length) {
		var nd = {"rows":[], "total_count":0, "pos":0};
		var count = 0;
		for (var i in data.rows) {
			if (ids.indexOf(data.rows[i].id.toString())<0) {
				data.rows[i].data[noInd] = count+1;
				nd.rows.push(data.rows[i]);
				count++;
			}
		}
		nd["total_count"] = count;
		data = nd;
	}
	return data;
}

//add new column in result data
function grid_addColsToData(data, pre, newd, defaults) {
	if (!data || !data.rows || !data.rows.length) return;
	for (var i in data.rows) {
		if (pre) {
			data.rows[i].data = newd.concat(data.rows[i].data);
		} else {
			data.rows[i].data = data.rows[i].data.concat(newd);
		}
		if (defaults) {
			for (var j=0; j<data.rows[i].data.length; j++) {
				if (defaults[j] && (data.rows[i].data[j]==undefined || data.rows[i].data[j]=='')) {
					data.rows[i].data[j] = defaults[j];
				}
			}
		}
	}
}

//set json column data to string data
function grid_jsoncolumnToStrInGridJson(_gridJson, columnIndixes) {
	if (_gridJson==undefined || _gridJson.rows==undefined || _gridJson.length==0) {
		return;
	}
	for (var i in _gridJson.rows) {
		for (var j in columnIndixes) {
			var _jsoncoldata = _gridJson.rows[i]["data"][columnIndixes[j]];
			var _newcoldata = '';
			if (undefined!=_jsoncoldata) {
				_newcoldata = JSON.stringify(_jsoncoldata);
			}
			_gridJson.rows[i]["data"][columnIndixes[j]] = _newcoldata;
		}
	}
}

//set i18n info into data
function grid_setI18nInfoToGridJson(_gridjson, _columni18n, _delta) {
	if (undefined==typeof(_delta)) {
		_delta = 0;
	}
	for (var j in _columni18n) {
		for (var i in _gridjson.rows) {
			_gridjson.rows[i]["data"][parseInt(j)+_delta] += pairro_spliter + _columni18n[j][_gridjson.rows[i]["data"][parseInt(j)+_delta]];
		}
	}
}

//set i18n info into data
function grid_setI18nInfoToGridJsonByCId(_gridObj, _gridjson, _columni18n, _delta) {
	var delta = 0;
	if (!isNaN(_delta)) {
		delta = _delta;
	}
	for (var j in _columni18n) {
		var ind = _gridObj.getColIndexById(j) - delta;
		for (var i in _gridjson.rows) {
			_gridjson.rows[i]["data"][ind] += pairro_spliter + _columni18n[j][_gridjson.rows[i]["data"][ind]];
		}
	}
}

//分页清除
dhtmlXGridObject.prototype.clearAllInPaging=function(a){if(this.obj.rows[0]){if(this._h2&&(this._h2=new dhtmlxHierarchy,this._fake))this._realfake?this._h2=this._fake._h2:this._fake._h2=this._h2;this.limit=this._limitC=0;this.editStop(!0);this._dLoadTimer&&window.clearTimeout(this._dLoadTimer);if(this._dload)this.objBox.scrollTop=0,this.limit=this._limitC||0,this._initDrF=!0;for(var b=this.rowsCol.length,b=this.obj.rows.length,c=b-1;c>0;c--){var d=this.obj.rows[c];d.parentNode.removeChild(d)}if(a){this._master_row=null;this.obj.rows[0].parentNode.removeChild(this.obj.rows[0]);for(c=this.hdr.rows.length-1;c>=0;c--)d=this.hdr.rows[c],d.parentNode.removeChild(d);if(this.ftr)this.ftr.parentNode.removeChild(this.ftr),this.ftr=null;this._aHead=this.ftr=this.cellWidth=this._aFoot=null;this.cellType=dhtmlxArray();this._hrrar=[];this.columnIds=[];this.combos=[];this._strangeParams=[];this.defVal=[];this._ivizcol=null}this.cell=this.row=null;this.rowsCol=dhtmlxArray();this.rowsAr={};this._RaSeCol=[];this.rowsBuffer=dhtmlxArray();this.UserData=[];this.selectedRows=dhtmlxArray();this._contextCallTimer&&window.clearTimeout(this._contextCallTimer);this._sst&&this.enableStableSorting(!0);this._fillers=this.undefined;this.setSortImgState(!1);this.setSizes();this.callEvent("onClearAll",[])}};


/**
 * bind coro combo in grid
 * @param options
 * @param rId
 * @param cId
 * @param list1
 * @param defaultValue
 */
dhtmlXGridObject.prototype.grid_bindCombo = function(rId, cId, list1, options, defaultValue) {
	var ct = "coro";
	if(options && options.readonly) {
		ct = "rocoro";
	} else {
		ct = options && options.editable ? "co" : "coro";
	}
	this.setCellExcellType(rId,cId, ct);
	if(!list1) return;
	var combo1 = this.getCustomCombo(rId,cId);
	if (options) {
		options.comboSize && combo1.setSize(options.comboSize);
		options.comboWidth && combo1.setOptionWidth(options.comboWidth);
	}
	combo1.clear();
	for (var i=0;i<list1.length;i++) {
		combo1.put(list1[i][0], list1[i][1]);
	}
	this.cells(rId,cId).setValue(defaultValue!=undefined?defaultValue:list1[0][0]);
};

dhtmlXGridObject.prototype.grid_bindColCombo = function(cId, list1, options) {
	var ct = "coro";
	if(options && options.readonly) {
		ct = "rocoro";
	} else {
		ct = options && options.editable ? "co" : "coro";
	}
	this.setColumnExcellType(cId, ct);
	if(!list1) return;
	var combo1 = this.getCombo(cId);
	if (options) {
		options.comboSize && combo1.setSize(options.comboSize);
		options.comboWidth && combo1.setOptionWidth(options.comboWidth);
	}
	combo1.clear();
	for (var i=0;i<list1.length;i++) {
		combo1.put(list1[i][0], list1[i][1]);
	}
};

/**get order columns
*/
dhtmlXGridObject.prototype.grid_getOrderColumns = function() {
	return this['_grid_ordercolumns'];
};

/**set order columns
*/
dhtmlXGridObject.prototype.grid_setOrderColumns = function(ordercolumns) {
	this['_grid_ordercolumns'] = ordercolumns;
};

/**add order column
*/
dhtmlXGridObject.prototype.grid_setColumnOrder = function(_cId) {
	if (!_cId) return;
	if (this['_grid_ordercolumns']==undefined) {
		this['_grid_ordercolumns'] = [];
	}
	var _orcs = this['_grid_ordercolumns'];
	var _orcsnew = [];
	var _dr = "ASC";
	for (var i in _orcs) {
		//alert(_orcs[i][0]+'    '+_cId);
		var f = false;
		for (var key in _orcs[i]) {
			if(key==_cId) {
				//change direction
				if ('ASC'==_orcs[i][_cId]) {
					_dr = 'DESC';
				}
				f = true;
			}
		}
		if (!f) {
			_orcsnew.push(_orcs[i]);
		}
	}
	//add new to first
	var oc = new Object();
	oc[_cId] = _dr;
	_orcsnew.unshift(oc);
	this['_grid_ordercolumns'] = _orcsnew;
	return _dr;
};

//set sort image
dhtmlXGridObject.prototype.grid_setOrderImg = function(ind, _direct) {
	if (!ind || !_direct || !this.hdr.rows) {
		return;
	}
	var _newimg = '<img align="absmiddle" src="'+dhtmlx.image_path + 'sort_'+_direct.toLowerCase()+'.gif" style="align:absmiddle;float:right"></img>';
	if (undefined != this.hdr.rows[1].childNodes[ind].childNodes[0].childNodes[1]) {
		this.hdr.rows[1].childNodes[ind].childNodes[0].childNodes[1].src=dhtmlx.image_path + 'sort_'+_direct.toLowerCase()+'.gif';
	} else {
		this.hdr.rows[1].childNodes[ind].childNodes[0].innerHTML += _newimg;
	}
};

//parse data and set total number
dhtmlXGridObject.prototype.parseJson = function(_data) {
	this.parse(_data, 'json');
	if (!isNaN(_data.total_count) && this._pgn_parentObj) {
		var pagedivwrapper = $(this._pgn_parentObj).children().eq(0);
		var totaldiv = pagedivwrapper.find('.gridtotaldiv');
		if (!totaldiv || totaldiv.length==0) {
			pagedivwrapper.append('<div class="gridtotaldiv dhx_toolbar_text"></div>');
			totaldiv = pagedivwrapper.find('.gridtotaldiv');
		}
		totaldiv.html('&nbsp;&nbsp;'+dhtmlXGridObject.prototype.i18n.paging.total+' : '+((_data && _data.total_count) ? _data.total_count : 0));
	}
};

//set total number
dhtmlXGridObject.prototype.grid_setTotal = function(pagingareaId, _data) {
	var pagedivwrapper = $("#"+pagingareaId).find(".float_left");
	var totaldiv = pagedivwrapper.find('.gridtotaldiv');
	if (!totaldiv || totaldiv.length==0) {
		pagedivwrapper.append('<div class="gridtotaldiv dhx_toolbar_text"></div>');
		totaldiv = pagedivwrapper.find('.gridtotaldiv');
	}
	totaldiv.html('&nbsp;&nbsp;'+dhtmlXGridObject.prototype.i18n.paging.total+' : '+((_data && _data.total_count) ? _data.total_count : 0));
};

//rewrite event handler for onHeaderClick
function grid_onHeaderClick(ind,obj){
	if (this.getRowsNum()==undefined || this.getRowsNum()==0) {
		return;
	}
	if ('na'==this.fldSort[ind]) {
		return;
	}
	var _cId = this.getColumnId(ind);
	var _direct = this.grid_setColumnOrder(_cId);
	this.grid_setOrderImg(ind, _direct);
	this.refreshPaging();
}

//refresh
dhtmlXGridObject.prototype.refreshPaging = function() {
	var _curPage = this.getStateOfView()[0];
	if (_curPage!=undefined) {
		this.changePage(_curPage);
	}
};

//toLastPage
dhtmlXGridObject.prototype.toLastPage = function() {
	var sv = this.getStateOfView();
	if (sv!=undefined) {
		this.changePage(Math.ceil(sv[3]/this.rowsBufferOutSize));
	}
};

//set language
dhtmlXGridObject.prototype.setLang = function(lang) {
	this._lang = lang;
};

//set language, default is english
dhtmlXGridObject.prototype.getLang = function() {
	if (!this._lang) {
		this._lang = 'en';
	}
	return this._lang;
};

//set custom excell types after init
dhtmlXGridObject.prototype.setCustomColumnExcellTypes = function(_ct) {
	for (var i in _ct) {
		this.setColumnExcellType(this.getColIndexById(i), _ct[i]);
	}
};

//get excell type of cell
dhtmlXGridObject.prototype.getCellExcellType = function (_rowid, ind) {
	return this.cells(_rowid,ind).cell._cellType;
};

/**checkAllInCol
*/
dhtmlXGridObject.prototype.grid_checkAllInCol = function(cInd) {
	this.forEachRow(function(rid){
		this.cells(rid,cInd).setValue(1);
	});
};

/**unCheckAllInCol
*/
dhtmlXGridObject.prototype.grid_unCheckAllInCol = function(cInd) {
	this.forEachRow(function(rid){
		this.cells(rid,cInd).setValue(0);
	});
};

/**reverseCheckInCol
*/
dhtmlXGridObject.prototype.grid_reverseCheckInCol = function(cInd) {
	this.forEachRow(function(rid){
		this.cells(rid,cInd).setValue("1"==this.cells(rid,cInd).getValue() ? 0 : 1);
	});
};

/**delete checked rows
*/
dhtmlXGridObject.prototype.grid_deleteChecked = function(cInd, data) {
	var rids = this.getCheckedRows(cInd);
	if (!rids) return;
	var rida = rids.split(",");
	for (var i=rida.length-1; i>=0; i--) {
		this.deleteRow(rida[i]);
	}
	return rida;
};

//reset counter col
dhtmlXGridObject.prototype.resetCounter = function(cInd) {
	var rn = this.getRowsNum();
	for (var i=0; i<rn; i++) {
		this.cellByIndex(i, cInd).setValue(i+1);
	}
};

//get row data
dhtmlXGridObject.prototype.getRowData = function(rId) {
	var ridx = this.getRowIndex(rId);
	if (ridx<0) return null;
	var cols = this.getColumnsNum();
	var rtn = [];
	for (var i=0; i<cols; i++) {
		rtn.push(this.cells(rId, i).getValue());
	}
	return rtn;
};

//get row data
dhtmlXGridObject.prototype.getRowDataWithId = function(rId) {
	var ridx = this.getRowIndex(rId);
	if (ridx<0) return null;
	var cols = this.getColumnsNum();
	var rtn = {};
	for (var i=0; i<cols; i++) {
		rtn[this.getColumnId(i)] = this.cells(rId, i).getValue();
	}
	return rtn;
};

//filter grid data just before load
dhtmlXGridObject.prototype.filterDataByCols = function(_gridjson, colIds, func) {
	if (!colIds || !colIds.length) return;
	for (var j in colIds) {
		var idx = this.getColIndexById(colIds[j]);
		for (var i in _gridjson.rows) {
			_gridjson.rows[i].data[idx] = func(_gridjson.rows[i].data[idx]);
		}
	}
};

//get result columns from metadata
function grid_getResultColumnsInfoFromGridInfo(_metadata) {
	var _cols = _metadata.column;
	var _dtypes = _metadata.displaytype.split(',');
	var _rscols = [];
	for (var i=0; i<_cols.length; i++) {
		var _alias = _cols[i];
		var _indx = _alias.indexOf('_');
		var _column = _alias.substr(0, _indx) + '.' + _alias.substr(_indx+1);
		_rscols.push({"column":_column,"alias":_alias,"type":_dtypes[i]});
	}
	return _rscols;
}

//set current page, return if the page is changed
/*function grid_setCurpage(pageGlobalVar, pageInd) {
	if (pageGlobalVar.currentPage==undefined || pageGlobalVar.currentPage!=pageInd) {
		pageGlobalVar.currentPage = pageInd;
		return true;
	}
	return false;
}*/

//reverse boolean string like 'true,true,false' to 'false,false,true'
function grid_reverseBoolstr(bstr) {
	if (bstr==null || bstr=='') {
		return '';
	}
	var bstrl = bstr.split(",");
	var rtn = '';
	for (var i=0; i<bstrl.length; i++) {
		if (i>0) {
			rtn += ',';
		}
		if ('true'==bstrl[i]) {
			rtn += 'false';
		} else {
			rtn += 'true';
		}
	}
	return rtn;
}


//get current page
/*function grid_getCurpage(pageGlobalVar) {
	return pageGlobalVar.currentPage;
}*/

/**
 *   @desc: generate print friendly view
 *   @type: public
 *   @edition: Professional
 *   @topic: 5
 */
dhtmlXGridObject.prototype.printView = function(before,after){
    var html="<style>TD { font-family:Arial; text-align:center; padding-left:2px;padding-right:2px; } \n td.filter input, td.filter select { display:none; }	\n  </style>";
    var st_hr=null;
    if (this._fake) {
        st_hr=[].concat(this._hrrar);
        for (var i=0; i<this._fake._cCount; i++)
            this._hrrar[i]=null;
    }
    html+="<base  href='"+document.location.href+"'></base>";
    if (!this.parentGrid) html+=(before||"");
    html += '<table width="100%" border="2px" cellpadding="0" cellspacing="0">';
    var row_length = Math.max(this.rowsBuffer.length,this.rowsCol.length); //paging and smartrendering
    var col_length = this._cCount;
    var width = this._printWidth();
    html += '<tr class="header_row_1">';
    for (var i=0; i<col_length; i++){
        if (this._hrrar && this._hrrar[i]) continue;
        var hcell=this.hdr.rows[1].cells[this.hdr.rows[1]._childIndexes?this.hdr.rows[1]._childIndexes[parseInt(i)]:i];
        var colspan=(hcell.colSpan||1);
        var rowspan=(hcell.rowSpan||1);

        for (var j=1; j<colspan; j++)
            width[i]+=width[j];
        html += '<td rowspan="'+rowspan+'" width="'+width[i]+'%" style="background-color:lightgrey;" colspan="'+colspan+'">'+this.getHeaderCol(i)+'</td>';
        i+=colspan-1;
    }
    html += '</tr>';

    for (var i=2; i<this.hdr.rows.length; i++){
        if (_isIE){
            html+="<tr style='background-color:lightgrey' class='header_row_"+i+"'>";
            var cells=this.hdr.rows[i].childNodes;
            for (var j=0; j < cells.length; j++)
                if (!this._hrrar || !this._hrrar[cells[j]._cellIndex]){
                    html+=cells[j].outerHTML;
                }
            html+="</tr>";
        }
        else
            html+="<tr class='header_row_"+i+"' style='background-color:lightgrey'>"+(this._fake?this._fake.hdr.rows[i].innerHTML:"")+this.hdr.rows[i].innerHTML+"</tr>";
    }

    for (var i=0; i<row_length; i++) {
        html += '<tr>';
        if (this.rowsCol[i] && this.rowsCol[i]._cntr){
            html+=this.rowsCol[i].innerHTML.replace(/<img[^>]*>/gi,"")+'</tr>';
            continue;
        }
        if (this.rowsCol[i] && this.rowsCol[i].style.display=="none") continue;

        var row_id
        if (this.rowsCol[i])
            row_id=this.rowsCol[i].idd;
        else if (this.rowsBuffer[i])
            row_id=this.rowsBuffer[i].idd;
        else continue; //dyn loading

        for (var j=0; j<col_length; j++) {
            if (this._hrrar && this._hrrar[j]) continue;
            if(this.rowsAr[row_id] && this.rowsAr[row_id].tagName=="TR") {
                var c=this.cells(row_id, j);
                if (c._setState) var value="";
                else if (c.getContent) value = c.getContent();
                else if (c.getImage || c.combo) var value=c.cell.innerHTML;
                else var value = c.getValue();
            } else
                var value=this._get_cell_value(this.rowsBuffer[i],j);
            var color = this.columnColor[j]?'background-color:'+this.columnColor[j]+';':'';
            var align = this.cellAlign[j]?'text-align:'+this.cellAlign[j]+';':'';
            var cspan =  c.getAttribute("colspan");
            html += '<td style="'+color+align+'" '+(cspan?'colSpan="'+cspan+'"':'')+'>'+(value===""?"&nbsp;":value)+'</td>';
            if (cspan) j+=cspan-1;
        }
        html += '</tr>';
        if (this.rowsCol[i] && this.rowsCol[i]._expanded){
            var sub=this.cells4(this.rowsCol[i]._expanded.ctrl);
            if (sub.getSubGrid)
                html += '<tr><td colspan="'+col_length+'">'+sub.getSubGrid().printView()+'</td></tr>';
            else
                html += '<tr><td colspan="'+col_length+'">'+this.rowsCol[i]._expanded.innerHTML+'</td></tr>';
        }
    }

    if (this.ftr)
        for (var i=1; i<this.ftr.childNodes[0].rows.length; i++)
            html+="<tr style='background-color:lightgrey'>"+((this._fake)?this._fake.ftr.childNodes[0].rows[i].innerHTML:"")+this.ftr.childNodes[0].rows[i].innerHTML+"</tr>";


    html += '</table>';
    if (this.parentGrid) return html;

    html+=(after||"");
    var d = window.open('', '_blank');
    d.document.write(html);
    d.document.write("<script>window.onerror=function(){return true;}</script>");
    d.document.close();
    if (this._fake) {
        this._hrrar=st_hr;
    }
}
dhtmlXGridObject.prototype._printWidth=function(){
    var width = [];
    var total_width = 0;
    for (var i=0; i<this._cCount; i++) {
        var w = this.getColWidth(i);
        width.push(w);
        total_width += w;
    }
    var percent_width = [];
    var total_percent_width = 0;
    for (var i=0; i<width.length; i++) {
        var p = Math.floor((width[i]/total_width)*100);
        total_percent_width += p;
        percent_width.push(p);
    }
    percent_width[percent_width.length-1] += 100-total_percent_width;
    return percent_width;
}

